//Замена наименований на странице с покупками
(function($) {
    if (window.location.pathname === '/sales/control/userProduct/my') {
        function replaceProductsText() {
            $('*:not(script):not(style)').contents().each(function() {
                if (this.nodeType === Node.TEXT_NODE && 
                    this.textContent.includes('Купленные продукты')) {
                    this.textContent = this.textContent.replace(/Купленные продукты/g, 'Покупки');
                }
            });
        }
        function replaceSubscriptionInHeaders() {
            $('th').each(function() {
                const $th = $(this);
                const text = $th.text().trim();
                if (text === 'Подписка') {
                    $th.text('Покупка');
                } else if (text.includes('Подписка')) {
                    $th.text(text.replace(/Подписка/g, 'Покупка'));
                }
            });
        }
        function replaceAllText() {
            replaceProductsText();
            replaceSubscriptionInHeaders();
        }
        $(document).ready(function() {
            replaceAllText();
        });
        const observer = new MutationObserver(function() {
            replaceAllText();
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        // Для старых браузеров или дополнительной обработки AJAX
        $(document).on('DOMSubtreeModified', function() {
            clearTimeout(window.replaceTextTimeout);
            window.replaceTextTimeout = setTimeout(replaceAllText, 100);
        });
    }
})(jQuery);

// Удаление точки из кол-ва уроков и замена текста
const teachControlPathRegex = /\/teach\/control(\/.*)?/;
function processStreamElements() {
    const $elements = $('.stream-table tr td div b'); 
    if ($elements.length === 0) return;  
    $elements.each(function() {
        let text = $(this).text().replace('.', '');
        $(this).text(text);
    });
}
function processLessonDates() {
    $('.user-state-label.has-start-at.lesson-date').each(function() {
        let text = $(this).text()
            .replace('Дата и время начала', '')
            .replace('(стоп-урок)', '')
            .trim();
        $(this).text(text);
    });
}
$(document).ready(function() {
    const currentPath = window.location.pathname;
    if (teachControlPathRegex.test(currentPath)) {
        processStreamElements();
        processLessonDates();
    }
});

//Добавление галочки для выполненного урока
document.addEventListener('DOMContentLoaded', function() {
  const accomplishedLessons = document.querySelectorAll('.lesson-list li.user-state-accomplished'); 
  accomplishedLessons.forEach(lesson => {
    if (!lesson.querySelector('.accomplished-checkmark')) {
      const checkmark = document.createElement('span');
      checkmark.className = 'accomplished-checkmark';
      checkmark.innerHTML = '✓';
      const titleElement = lesson.querySelector('.title');
      if (titleElement) {
        titleElement.appendChild(checkmark);
      } else {
        lesson.appendChild(checkmark);
      }
    }
  });
});

//Замена плейсхолдера в комментариях
$(document).ready(function() {
  const textarea = $('.new-comment-textarea.new-comment-textarea-level-1.emoji-textarea');

  if (textarea.length) {
    textarea.attr('placeholder', 'Добавить комментарий');
  } else {
    console.error('Элемент с указанными классами не найден');
  }
});

//Добавление div в карточки уроков для описания
document.addEventListener('DOMContentLoaded', function() {
  const vmiddleElements = document.querySelectorAll('.lesson-list li .info .vmiddle');
  
  vmiddleElements.forEach(vmiddle => {
    const descriptions = vmiddle.querySelectorAll('.description');
    
    if (descriptions.length > 0) {
      const container = document.createElement('div');
      container.className = 'description-container';
      
      descriptions.forEach(desc => {
        container.appendChild(desc.cloneNode(true));
        desc.remove();
      });
      
      vmiddle.appendChild(container);
    }
  });
  
  console.log('Всё чики-пуки');
});